<template>
  <md-nav-bar title="队员报名" :showLeft="false" />
  <view class="container">
    <uni-forms ref="form" :modelValue="data.formData" :rules="data.rules" label-position="top" label-width="100">
      <uni-forms-item
        label="邀请码"
        name="invite_code"
        required
        :rules="[
          {
            required: true,
            errorMessage: '请输入邀请码',
          },
        ]">
        <uni-easyinput
          type="text"
          v-model="data.formData.invite_code"
          placeholder="请输入邀请码"
          :input-border="false"
          @blur="blurInviteCode" />
      </uni-forms-item>

      <!-- 针对队员展示 -->
      <view v-if="data.teamInfo?.title" style="margin-bottom: 20px">
        <view class="text-label">队伍名称</view>
        <view class="form-item text-content">{{ data.teamInfo?.title }}</view>
      </view>

      <!-- 添加报名人按钮 -->
      <view class="add white" type="primary" @click="handleJumpEnterList" style="margin-bottom: 20px">+添加报名人</view>

      <uni-forms-item label="证件类型" name="id_type" required>
        <view class="form-item" style="padding: 0">
          <uni-data-select
            v-model="data.formData.id_type"
            :localdata="data.idTypeList"
            :clear="false"></uni-data-select>
        </view>
      </uni-forms-item>
      <uni-forms-item :label="data.formData.id_type == 1 ? '身份证信息面' : '证件照'" name="front_img" required>
        <view class="form-item">
          <uni-file-picker
            return-type="object"
            file-mediatype="image"
            :imageStyles="{ width: '200rpx', height: '140rpx' }"
            v-model="data.formData.front_img"
            @select="e => handleUpload(e, 'front_img')">
            <md-icon type="bg" name="id_front" width="200" height="140" />
          </uni-file-picker>
        </view>
      </uni-forms-item>
      <uni-forms-item v-if="data.formData.id_type == 1" label="身份证国徽面" name="back_img" required>
        <view class="form-item">
          <uni-file-picker
            return-type="object"
            file-mediatype="image"
            :imageStyles="{ width: '200rpx', height: '140rpx' }"
            v-model="data.formData.back_img"
            @select="e => handleUpload(e, 'back_img')">
            <md-icon type="bg" name="id_back" width="200" height="140" />
          </uni-file-picker>
        </view>
      </uni-forms-item>
      <uni-forms-item label="姓名" name="truename" required>
        <view class="form-item flex-c" style="padding: 0 20rpx 0 0">
          <uni-easyinput type="text" v-model="data.formData.truename" placeholder="请输入姓名" :input-border="false" />
        </view>
      </uni-forms-item>
      <uni-forms-item label="性别" name="sex" required>
        <view class="form-item">
          <uni-data-checkbox v-model="data.formData.sex" :localdata="data.sex"></uni-data-checkbox>
        </view>
      </uni-forms-item>
      <uni-forms-item label="证件号" name="idcard" required>
        <uni-easyinput type="text" v-model="data.formData.idcard" placeholder="请输入证件号" :input-border="false" />
      </uni-forms-item>
      <uni-forms-item label="出生日期" name="birth" required>
        <uni-datetime-picker type="date" :clear-icon="false" v-model="data.formData.birth" :border="false" />
      </uni-forms-item>
      <!-- <uni-forms-item label="上传体检报告" name="report_img">
        <view class="form-item">
          <uni-file-picker
            return-type="object"
            limit="1"
            file-mediatype="image"
            :imageStyles="{ width: '200rpx', height: '140rpx' }"
            v-model="data.formData.report_img"
            @select="e => handleUpload(e, 'report_img')">
            <md-icon type="bg" name="mr_front" width="200" height="140" />
          </uni-file-picker>
        </view>
      </uni-forms-item> -->
      <uni-forms-item label="报名组别" name="group" v-if="data.teamInfo?.group_name">
        <view class="form-item text-content">{{ data.teamInfo.group_name }}</view>
      </uni-forms-item>
      <uni-forms-item label="报名人数" name="sign_num">
        <view class="form-item text-content">
          {{ data.formData?.sign_num || data.teamInfo?.sign_num }}
        </view>
      </uni-forms-item>
      <!-- <uni-forms-item label="服装尺码" name="size" required>
        <view class="form-item" style="padding: 0">
          <uni-data-select v-model="data.formData.size" :localdata="data.sizeList" />
        </view>
      </uni-forms-item> -->
      <uni-forms-item label="联系电话" name="mobile" required>
        <uni-easyinput type="text" v-model="data.formData.mobile" placeholder="请输入联系电话" :input-border="false" />
      </uni-forms-item>
      <uni-forms-item label="紧急联系人" name="contact" required>
        <uni-easyinput
          type="text"
          v-model="data.formData.contact"
          placeholder="请输入紧急联系人"
          :input-border="false" />
      </uni-forms-item>
      <uni-forms-item label="紧急联系人电话" name="contact_mobile" required>
        <uni-easyinput
          type="text"
          v-model="data.formData.contact_mobile"
          placeholder="请输入紧急联系人电话"
          :input-border="false" />
      </uni-forms-item>
    </uni-forms>
    <!-- 添加成员 -->
    <view class="card">
      <view class="forms-item-label">添加成员</view>
      <view class="form-item-content">
        <view class="member-list">
          <view class="member-item" v-for="item in data.memberList" :key="item.id">
            <view class="del-btn">
              <md-icon name="delete" width="31" height="31" @click="del(item.id)" />
            </view>
            <view v-for="field in item.fields" :key="field.name">{{ field.value }}</view>
          </view>
          <view class="add" type="primary" @click="add">+添加老人或者小孩</view>
        </view>
      </view>
    </view>
    <!-- 提交按钮 -->
    <view class="m-top-40">
      <md-button class="submit" @click="submit">提交</md-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from '@dcloudio/uni-app';
import { reactive, ref } from 'vue';
// 接口
import { check_ocr_identity, getTeamInfo, signTeamMember, uploadImage, userSignConfig } from './service';
import type { SignTeam } from '@/api/data';
// 工具
import { formatSignValue, formatSignSubmitValue } from '../registration/util';
import { Toast } from '@/utils/util';

const data = reactive<any>({
  active_id: -1,
  sign_team_id: -1, // 队伍id
  formData: {
    title: '',
    truename: '',
    idcard: '',
    sex: 1,
    birth: null,
    id_type: 1,
    group: '',
    sign_num: '',
    size: '',
    mobile: '',
    contact: '',
    contact_mobile: '',
    front_img: {},
    back_img: {},
  },
  memberList: [], // 成员添加
  rules: {
    title: {
      rules: [
        {
          required: true,
          errorMessage: '请输入队伍名称',
        },
      ],
    },
    truename: {
      rules: [
        {
          required: true,
          errorMessage: '请输入姓名',
        },
      ],
    },
    idcard: {
      rules: [
        {
          required: true,
          errorMessage: '请输入身份证',
        },
      ],
    },
    sex: {
      rules: [
        {
          required: true,
          errorMessage: '请选择性别',
        },
      ],
    },
    birth: {
      rules: [
        {
          required: true,
          errorMessage: '请选择出生日期',
        },
      ],
    },
    id_type: {
      rules: [
        {
          required: true,
          errorMessage: '请选择证件类型',
        },
      ],
    },
    size: {
      rules: [
        {
          required: true,
          errorMessage: '请选择服装尺寸',
        },
      ],
    },
    mobile: {
      rules: [
        {
          required: true,
          errorMessage: '请输入联系电话',
        },
      ],
    },
    contact: {
      rules: [
        {
          required: true,
          errorMessage: '请输入紧急联系人',
        },
      ],
    },
    contact_mobile: {
      rules: [
        {
          required: true,
          errorMessage: '请输入紧急联系人电话',
        },
      ],
    },
    front_img: {
      rules: [{ required: true, errorMessage: '请上传身份证信息面' }],
    },
    back_img: {
      rules: [{ required: true, errorMessage: '请上传身份证国徽面' }],
    },
  },
  sex: [
    {
      text: '男',
      value: 1,
    },
    {
      text: '女',
      value: 2,
    },
  ],
  idTypeList: [], // 证件类型下拉
  sizeList: [], // 服装尺寸下拉
  groupList: [], // 组别下拉
  teamInfo: {}, // 队伍信息
});

const form = ref(null);
const isLeader = ref<boolean>(true);
const openType = ref('page');

const setfields = (vals: any) => [
  { label: '姓名', name: 'truename', value: vals?.truename },
  { label: '性别', name: 'sex', value: vals?.sex === 1 ? '男' : '女' },
  { label: '出生日期', name: 'birth', value: vals?.birth },
  { label: '电话', name: 'mobile', value: vals?.mobile },
];

function add() {
  isLeader.value = false;
  uni.navigateTo({
    url: '/pages/outside-h5/userlist?type=select',
  });
}

function del(id: number) {
  uni.showModal({
    title: '提示',
    content: '是否删除该成员？',
    success: res => {
      if (res.confirm) {
        let index = data.memberList.findIndex(v => v.id === id);
        data.memberList.splice(index, 1);
      }
    },
  });
}

// 触发提交表单
const submit = async () => {
  try {
    const res = await form.value?.validate();
    // console.log('表单数据信息：', res);
    // 成员
    const team_ids: string = data.memberList?.map((item: { id: string }) => item.id)?.join(',') || '';

    // 【队员报名】
    // 活动id处理
    const active_id = data?.active_id || data.teamInfo?.active_id;
    //  邀请码处理
    const invite_code = res?.invite_code || data.teamInfo?.invite_code;
    signTeamMember({
      active_id,
      ...formatSignSubmitValue(res),
      team_ids,
      title: undefined,
      group: undefined,
      sign_num: undefined,
      invite_code,
    }).then(res => {
      uni.showModal({
        title: '提示',
        content: res?.msg || '报名成功',
        showCancel: false,
      });
    });
  } catch (e) {
    //TODO handle the exception
    console.log('表单错误信息：', e);
    e?.length && Toast(e?.[e?.length - 1]?.errorMessage);
  }
};

// 跳转录入的队员列表选择
const handleJumpEnterList = () => {
  isLeader.value = true;
  uni.navigateTo({
    url: '/pages/outside-h5/userlist?type=select',
  });
};

// 邀请码失焦事件
const blurInviteCode = (e: any) => {
  const { value } = e.detail;
  console.log('邀请码：', value);
  value && fetchGetTeamInfo({ invite_code: value });
};

/**
 * 上传相关
 */
const handleUpload = (e: any, type: string) => {
  // console.log('选择文件：', e);
  let { tempFilePaths } = e;
  uni.showLoading({
    title: '图片上传中...',
    mask: true,
  });
  uploadImage({ tempFilePaths, formData: { category: 'sign', active_id: data.active_id } }).then(async res => {
    // console.log(res);
    const obj = {
      url: res.data.url,
      extname: 'png',
      name: type + '.png',
    };
    if (data.formData.id_type == 1 && type === 'front_img') {
      const info = await fetchCheckOcrIdentity(res?.data?.url);
      data.formData = { ...data.formData, ...info };
    }
    data.formData[type] = obj;
    uni.hideLoading();
  });
};

/**
 * 接口相关
 */
// 获取其他下拉数据
const fetchUserSignIndex = async () => {
  try {
    const res = await userSignConfig();
    data.idTypeList = res.data?.id_type || [];
    data.sizeList = res.data?.size_type || [];
    return true;
  } catch (error) {}
  return false;
};

// 校验身份证图片
const fetchCheckOcrIdentity = async (front_img: string) => {
  try {
    const res = await check_ocr_identity(front_img);
    return res.data;
  } catch (error) {}
  return undefined;
};

// 查询队伍信息
const fetchGetTeamInfo = async (params: Partial<SignTeam.Info.Query>) => {
  if (!params.invite_code && params.sign_team_id == -1) return;
  try {
    const res = await getTeamInfo(params);
    data.teamInfo = res.data;
  } catch (error) {}
};

onLoad(option => {
  data.active_id = option?.active_id;
  data.formData.sign_num = option?.sign_num; // 处理报名数量
  data.sign_team_id = option?.sign_team_id || -1;
  data.formData.invite_code = option?.invite_code;
  // 通过什么方式打开的页面 page | share
  openType.value = option?.openType || 'page';
  // 接口调用
  uni.showLoading({
    title: '加载中',
  });
  Promise.all([
    fetchUserSignIndex(),
    fetchGetTeamInfo({
      sign_team_id: option?.sign_team_id || -1,
      invite_code: option?.invite_code || '',
    }),
  ]).finally(() => {
    uni.hideLoading();
  });
});

onShow(() => {
  const selectUser = uni.getStorageSync('selectUser');
  if (selectUser) {
    const _selectUser = JSON.parse(selectUser);
    // console.log(_selectUser);
    if (isLeader.value) {
      data.formData = formatSignValue({
        ...data.formData,
        ..._selectUser,
        sign_num: data.formData.sign_num || data.teamInfo?.sign_num,
      });
    } else {
      data.memberList.push({
        fields: setfields(_selectUser),
        id: _selectUser?.id || Date.now(),
      });
    }
    uni.removeStorageSync('selectUser');
  }
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  .forms-item-label {
    height: 36px;
    line-height: 36px;
    padding-bottom: 10px;
    font-size: 14px;
    color: #606266;
  }
  .text-label {
    height: 28px;
    line-height: 28px;
    font-size: 14px;
    color: #606266;
    padding-bottom: 8px;
    box-sizing: border-box;
  }
  .form-item {
    background: white;
    border-radius: 10rpx;
    padding: 10rpx 0 10rpx 10px;
    &.text-content {
      height: 30px;
      line-height: 30px;
      font-size: 14px;
    }
  }
  .form-item-content {
    padding: 16rpx;
    background: white;
  }
  .form-item-row {
    position: relative;
    .del-button {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
  .member-list {
    .del-btn {
      position: absolute;
      top: 0;
      right: 0;
    }
    .member-item {
      position: relative;
      width: 100%;
      height: 80rpx;
      background: #f7f7f7;
      border-radius: 10rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24rpx;
      box-sizing: border-box;
      margin-bottom: 20rpx;
    }
  }
  .add {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background: #f7f7f7;
    border-radius: 10rpx;
    color: #b3b3b3;
    font-size: 28rpx;
    text-align: center;
    &.white {
      background: white;
      color: $title;
    }
  }
}
</style>
